package com.library;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/list_book")
public class ListBookServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setContentType("application/json; charset=UTF-8");

        List<Book> books = BookDAO.listAllBooks();
        PrintWriter out = response.getWriter();
        out.print("[");
        for (int i = 0; i < books.size(); i++) {
            Book book = books.get(i);
            out.print("{");
            out.print("\"number\": \"" + book.getNumber() + "\"");
            out.print(", \"name\": \"" + book.getName() + "\"");
            out.print(", \"author\": \"" + book.getAuthor() + "\"");
            out.print("}");
            if (i < books.size() - 1) {
                out.print(",");
            }
        }
        out.print("]");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }
}

